package com.vdong.common.oauth.web.controller;


import com.alibaba.fastjson.JSON;
import com.vdong.common.oauth.common.enums.AuthorizeTypeEnum;
import com.vdong.common.oauth.common.exception.WebBizException;
import com.vdong.common.oauth.service.WechatAuthorizerInfoService;
import com.vdong.common.oauth.service.WechatService;
import com.vdong.common.oauth.service.impl.WeixinService;
import org.apache.commons.lang3.StringUtils;
import org.lamb.framework.core.security.LambPrincipalFactoryContainer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import springfox.documentation.annotations.ApiIgnore;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Controller
@RequestMapping("/")
public class WechatController {

    private static Logger logger = LoggerFactory.getLogger(WechatController.class);

    @Autowired
    private WeixinService weixinService;

    @Autowired
    private WechatAuthorizerInfoService wechatAuthorizerInfoService;

    @Autowired
    private WechatService wechatService;


    /**
     * 授权事件接收-公众号第三方平台
     * 开放平台每隔10分钟持续推送component_verify_ticket
     */
    @RequestMapping(value = "/notify", method = RequestMethod.POST)
    public void notify(String msg_signature, String timestamp, String nonce, HttpServletRequest request, HttpServletResponse response) throws Exception {
        weixinService.processNotify(msg_signature, timestamp, nonce, request);
        response.getWriter().write("success");
        response.getWriter().close();
    }

    /**
     * 授权公众号消息交互
     */
    @RequestMapping(value = "/{appid}/message", method = RequestMethod.POST)
    public void message(@PathVariable("appid") String appid, HttpServletRequest request, HttpServletResponse response) throws Exception {
        //设置正确的 content-type 以防止中文乱码
        response.setContentType("text/xml;charset=UTF-8");
        String result = weixinService.processMessage(request, appid);
        response.getWriter().write(result);
        response.getWriter().close();
    }

    /**
     * 绑定授权给第三方平台的url
     */
    @ApiIgnore
    @RequestMapping(value = "componentloginpagenew", method = RequestMethod.GET)
    public String componentloginpagenew( @RequestParam(defaultValue = "2") Integer authorizeType) {
        logger.info("绑定授权给第三方平台的url");
//        storeId = (storeId == null ? SecurityUtil.loginStoreId() : storeId);
        String url = wechatService.getAuthUrlNew(-1L, authorizeType);
        return "redirect:" + url;
    }

    @ApiIgnore
    @RequestMapping(value = "getCode", method = RequestMethod.GET)
    public String getCode(String code, String state, String appid) {
        if (StringUtils.isBlank(code) || StringUtils.isBlank(appid)) {
            throw new WebBizException("微信授权失败");
        }
        logger.info("小程序授权成功 storeId:{},appId:{},authCode:{}", state, appid, code);
        return "redirect:/wechat/auth/success";
    }


    /**
     * 新版微信公众号授权回调-保存授权信息
     */
    @RequestMapping(value = "saveAuthInfo/{storeId}/{authorizeType}", method = RequestMethod.GET)
    public String saveStoreAuthInfo(
            @PathVariable("storeId") Long storeId, @PathVariable("authorizeType") Integer authorizeType,
            String auth_code, Integer expires_in, RedirectAttributes attributes) {
        logger.info("小程序、公众号授权回调-保存授权信息 storeId:{},authCode:{},expires_in:{}", storeId, auth_code, expires_in);
        boolean isSuccess = true;
        String errorMsg = null;
        try {
            Boolean isOk = wechatAuthorizerInfoService.saveAuthInfo(storeId, auth_code, AuthorizeTypeEnum.getEnum(authorizeType));
            if (!isOk) {
                throw new WebBizException("保存授权信息失败");
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            isSuccess = false;
            errorMsg = e.getMessage();
        }
        if (errorMsg != null) {
            //attributes.addFlashAttribute("msg", URLEncoder.encode(errorMsg, "UTF-8"));
            attributes.addFlashAttribute("msg", errorMsg);
        }
        return isSuccess ? "redirect:/wechat/auth/success" : "redirect:/wechat/auth/fail";
    }




    /**
     * 授权保存跳转至成功页面
     */
    @RequestMapping(value = "auth/success", method = RequestMethod.GET)
    public String success() {
        return "success";
    }

    @RequestMapping(value = "auth/path", method = RequestMethod.GET)
    public String test() {
        return "test";
    }

    @RequestMapping(value = "/login2", method = RequestMethod.GET)
    public String login2() {
        return "login2";
    }
}
